$.extend($.fn.datagrid.defaults.editors, {
	password: {
		init: function(container, options) {
			var input = $('<input class="datagrid-editable-input"  type="password"/>').appendTo(container);
			return input;
		},
		getValue: function(target) {
			return $(target).val();
		},
		setValue: function(target, value) {
			$(target).val(value);
		},
		resize: function(target, width) {
			var input = $(target);
			if($.boxModel == true) {
				input.width(width - (input.outerWidth() - input.width()));
			} else {
				input.width(width);
			}
		}
	}
});
$.extend($.fn.validatebox.defaults.rules, {    
    endWith: {    
        validator: function(value,param){
        	var endStr = value.slice(-4);
            return endStr == param[0];    
        },    
        message: 'GIT地址必须以{0}结尾'   
    }    
});

window.onloadPage = function(){
	$("#systemTree").tree({
		url : contextPath + systemTreeUrl,
		animate : true,
		lines : true,
		onClick : function(node) {
			querySystemDetail(node);
		},
		onContextMenu: function(e,node){
             e.preventDefault();
             $(this).tree('select',node.target);
             if( node.id === 'systemCode' ) {
            	 $('#addSystem').menu('show',{
                     left: e.pageX,
                     top: e.pageY
                 }); 
             } else {
            	 $('#editSystem').menu('show',{
                     left: e.pageX,
                     top: e.pageY
                 });  
             }
             
         }
	});
} 

$(function(){
	$('body').pagewalkthrough({ 
        name: 'introduction', 
        steps: [{ 
           popup: { 
               content: '#walkthrough-1', 
               type: 'modal' 
           } 
        }, { 
            wrapper: '#systemTree', 
            popup: { 
                content: '#walkthrough-2', 
                type: 'tooltip', 
                position: 'right'
            } 
        }, { 
            wrapper: '#systemTree', 
            popup: { 
                content: '#walkthrough-3', 
                type: 'tooltip', 
                position: 'right' 
            } 
        }, { 
            wrapper: '#buttonSpan', 
            popup: { 
                content: '#walkthrough-4', 
                type: 'tooltip', 
                position: 'bottom' 
            } 
        }, { 
            wrapper: '#executeSpan', 
            popup: { 
                content: '#walkthrough-5', 
                type: 'tooltip', 
                position: 'right' 
            } 
        }] 
    }); 
	if($.cookie('cookie_key_pagewalkthrough') == null){
		$.cookie('cookie_key_pagewalkthrough', 'cookie_value_pagewalkthrough', { expires: 365 });
		$('body').pagewalkthrough('show'); 
	}
	$("#systemPanel").dialog('close');
	onloadPage();
	$("#dg").datagrid({
		iconCls: 'icon-edit',
        toolbar: '#tb',
        checkbox:true,
        singleSelect:false,
        onDblClickCell: onClickCell,
        onEndEdit: onEndEdit,
		columns:[[ {field:'environmentIndex',
					hidden:true
			      	},    
		          {field:'environmentType',
	        	  title:'环境',
	        	  width:80,
	        	  editor:{
                      type:'combobox',
                      options:{
                          valueField:'id',
                          textField:'name',
                          method:'get',
                          data:[{
                          	id :'DEV',
                          	name :'DEV'
                          },{
                          	id :'SIT',
                          	name :'SIT'
                          },{
                          	id :'UAT',
                          	name :'UAT'
                          },{
                        	id :'PRD',
                          	name :'PRD'
                          },{
                          	id :'OTHER',
                          	name :'OTHER'
                          }],
                           panelHeight:80,
                          required:true
                      }
                  }},    
		          {field:'dataBaseType',
            	  title:'数据库类型',
            	  width:70,
            	  editor:{
                      type:'combobox',
                      options:{
                          valueField:'id',
                          textField:'name',
                          method:'get',
                          data:[{
                          	id:'MYSQL',
                          	name :'MYSQL'
                          },{
                          	id:'ORACLE',
                          	name :'ORACLE'
                          }],
                          panelHeight:50,
                          required:true
                      }
                  }},    
		          {field:'dataBaseConnection',title:'数据库连接串',width:320,align:'center',editor:{type:'textbox',options:{required:true}}},
		          {field:'dataBaseUserName',title:'用户名',width:80,align:'center',editor:{type:'textbox',options:{required:true}}},
		          {field:'dataBasePassword',
	        	   title:'密码',
	        	   width:80,
	        	   align:'center',
	        	   formatter:function(value){return '******'},
	        	   editor:{type:'password',options:{required:true}}
	        	   },
		          {field:'currentIndex',title:'当前执行索引',width:80,align:'center',editor:{type:'numberbox',options:{required:true}}},
		          {field:'lastExecuteTime',title:'最后执行时间',width:150,align:'center'},
		          {field:'currentStatus',
	        	  title:'当前状态',
	        	  width:120,
	        	  align:'center',
	        	  formatter : function(value,row,index){
	        		  if(value === 'INIT'){
	        			  return '初始状态';
	        		  }
	        		  if (value === 'GITTING') {
	        			  return '正在从GIT中拉取代码';
	        		  }
	        		  if (value === 'SUCCESS') {
	        			  return '执行成功';
	        		  }
	        		  if (value === 'FAIL') {
	        			  return '执行失败';
	        		  }
	        		  if (value === 'EXECUTING') {
	        			  return '正在执行中';
	        		  }
	        	  }},
		          {field:'executeFailReason',
		        	  title:'失败原因',
		        	  width:100,
		        	  align:'center',
		        	  formatter : function(value,row,index){
		        		  if(value) {
		        			  return '<a href="javascript:void(0)" onclick = "showAllFailReason(\''+value.replace(/'/g,"\\'")+'\')">'+value.substring(0,5)+"..."+'</a>'
		        		  }
		        	  }
		        	  }
		      ]],
		onClickRow : function(rowIndex, rowData) {
			disableExecute();
		}
	});
	window.querySystemDetail = function(node){
		$.ajax({
			url : contextPath + systemDetailUrl,
			type : 'post',
			data : {systemCode:node.id},
			success : function(data){
				if(data){
					refresh(data.environments,data);
					$("#systemCode").html(data.systemCode);
					$("#pathType").html(data.pathType === 'git'?'GIT':'文件');
					$("#pathAddress").html(data.pathAddress);
					if(data.pathType === 'git'){
						$("#gitTr1").show();
						$("#gitTr2").show();
						$("#pathAddressTitle").html('GIT地址：');
						
						$("#gitUserName").html(data.gitUserName);
						$("#gitPassword").html('******');
						$("#gitBranch").html(data.gitBranch);
						$("#sqlPath").html(data.sqlPath);
					} else {
						$("#gitTr1").hide();
						$("#gitTr2").hide();
						$("#pathAddressTitle").html('文件名：');
						
					}
					$("#dg").datagrid({
						data:data.environments
					});
				}
				
			}
		});
	}
	
	$('#gitPathTypeBtn,#filePathTypeBtn').click(function(){
		if($(this).hasClass('trip-selected'))
			return;
		$(this).attr('class','trip-selected');
		if(this.id == 'gitPathTypeBtn'){
			$('#filePathTypeBtn').attr('class','trip-unselect');
			$('#pathTypeTree').val("git");
			pathTypeChange('git');
		} else {
			$('#gitPathTypeBtn').attr('class','trip-unselect');
			$('#pathTypeTree').val("file");
			pathTypeChange('file');
		}
  	});
});

window.showProcess = function(){
	$.messager.progress({
		title:'温馨提示',
		text : '请稍等...'
	})
}
window.closeProcess = function(){
	$.messager.progress('close');
}
window.showAllFailReason = function(reason) {
	$("#failResonWin").window({
		width:400,    
	    height:200,    
	    modal:true,
	    title:'失败原因明细',
	    content:reason
	});
}
	var editIndex = undefined;
   window.endEditing = function(){
        if (editIndex == undefined){return true}
        if ($('#dg').datagrid('validateRow', editIndex)){
            $('#dg').datagrid('endEdit', editIndex);
            editIndex = undefined;
            return true;
        } else {
            return false;
        }
    }
    window.onClickCell = function(index, field){
        if (editIndex != index){
            if (endEditing()){
                $('#dg').datagrid('selectRow', index)
                        .datagrid('beginEdit', index);
                var ed = $('#dg').datagrid('getEditor', {index:index,field:field});
                if (ed){
                    ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
                }
                editIndex = index;
            } else {
                setTimeout(function(){
                    $('#dg').datagrid('selectRow', editIndex);
                },0);
            }
        }
    }
    function onEndEdit(index, row){
        var ed = $(this).datagrid('getEditor', {
            index: index,
            field: 'environmentType'
        });
        row.environmentType = $(ed.target).combobox('getText');
    }
    function append(){
        if (endEditing()){
            $('#dg').datagrid('appendRow',{status:''});
            editIndex = $('#dg').datagrid('getRows').length-1;
            $('#dg').datagrid('selectRow', editIndex)
                    .datagrid('beginEdit', editIndex);
        }
    }
    function removeit(){
        if (editIndex == undefined){return}
        $('#dg').datagrid('cancelEdit', editIndex)
                .datagrid('deleteRow', editIndex);
        editIndex = undefined;
    }
   
    function accept(){
        if (endEditing()){
        	var rows = $('#dg').datagrid('getChanges');
        	var allDatas = $("#dg").datagrid('getRows');
        	var repeatFlag = false;
        	console.log(rows);
        	//判断是否重复环境
        	$.each(rows,function(i,row){
        		var count = 0;
        		$.each(allDatas,function(j,data){
        			if(row.environmentType == data.environmentType){
        				count ++;
        			}
        			if(count >= 2) {
        				repeatFlag = true;
        				return;
        			}
        		})
        	});
        	
        	if(repeatFlag){
        		$.messager.alert('温馨提示','环境不能重复','warning');
        		reject();
        		return;
        	}
            $('#dg').datagrid('acceptChanges');
            if(rows == null || rows === "" || rows.length === 0){
            	$.messager.alert('温馨提示','数据无变化，不需要更新','warning');
            	return;
            }
            var system = new Object();
        	system.systemCode = $("#systemCode").html();
        	system.environments = rows;
        	showProcess();
            $.ajax({
       		 url : contextPath + updateEnvironmentUrl,
       		type : 'post',
       		contentType : 'application/json',
       	    data : JSON.stringify(system),
       	    success : function(data){
       	    	closeProcess();
       	    	if (data.status === 'success') {
       	    		var node = $("#systemTree").tree('getSelected');
       	    		querySystemDetail(node);
       	    		$.messager.alert('温馨提示','更新成功','info');
       	    	} else {
       	    		$.messager.alert('温馨提示','更新失败','error');
       	    	}
       	    }
            });
        }
    }
    function reject(){
        $('#dg').datagrid('rejectChanges');
        editIndex = undefined;
    }
    function getChanges(){
         $('#dg').datagrid('getChanges');
    }
    var refreshIndex;
    function execute(){
    	var environments = $("#dg").datagrid('getSelections');
    	if(environments === null || environments === '' || environments === undefined || environments.length === 0 ){
    		$.messager.alert('温馨提示','请选择一条数据','warning');
    		return;
    	}
    	$("#execute").linkbutton('disable');
    	$("#removeEnvironment").linkbutton('disable');
    	$("#accept").linkbutton('disable');
    	$("#reject").linkbutton('disable');
    	var system = new Object();
    	system.systemCode = $("#systemCode").html();
    	system.environments = environments;
    	$.ajax({
    		 url : contextPath + executeUrl,
    		type : 'post',
    		contentType: 'application/json',
    	    data : JSON.stringify(system),
    	    success : function(data){
    	    	clearInterval(refreshIndex);//停止刷新
    	    	if(data){
    	    		refresh(environments,system);
    	    		if(data.status === 'fail' && data.failReason != ""){
    	    			$.messager.alert('温馨提示',data.failReason,'error');
        	    	} 
    	    	}
    	    	
    	    },
    	    error : function (data){
    	    	$.messager.alert('温馨提示',data.failReason,'error');
    	    	clearInterval(refreshIndex);//停止刷新
    	    }
    	});
    	  refreshIndex = setInterval(function(){
    		refresh(environments,system);
    		  }, 500);
    }
    /**
     * 更新执行是否可用
     */
    function disableExecute(){
    	var environments = $("#dg").datagrid('getSelections');
		if(environments != undefined && environments != null) {
			$("#execute").linkbutton('enable');
			$("#removeEnvironment").linkbutton('enable');
	    	$("#accept").linkbutton('enable');
	    	$("#reject").linkbutton('enable');
			$.each(environments,function(i,e){
				if (e.currentStatus === 'GITTING' || e.currentStatus === 'EXECUTING') {
					$("#execute").linkbutton('disable');
					$("#removeEnvironment").linkbutton('disable');
			    	$("#accept").linkbutton('disable');
			    	$("#reject").linkbutton('disable');
					return;
				}
			});
		}
    }
    /**
     * 刷新状态
     * @param environments
     * @param system
     */
    function refresh(environments,system){
    	$.ajax({
      		 url : contextPath + refreshStatusUrl,
      		 type : 'post',
      		 contentType: 'application/json',
      	     data : JSON.stringify(system),
      	     success : function(data){
      	    	if(data){
	   	   	    	for(var i = 0;i < data.length; i++) {
	   	   	    		var eType = data[i].environmentType;
	   	   	    		var eIndex = data[i].currentIndex;
	   	   	    		var eStatus = data[i].currentStatus;
	   	   	    		var eLastExecuteTime = data[i].lastExecuteTime;
	   	   	    		var eExecuteFailReason = data[i].executeFailReason;
	   	   	    		$.each(environments,function(j,e){
	   	   	    			if(eType === e.environmentType){
	   	   	    				var index = $("#dg").datagrid('getRowIndex',e);
	   	   	    				$("#dg").datagrid('updateRow',{
	   	   	    					index : index,
	   	   	    					row : {
	   	   	    						currentIndex : eIndex,
	   	   	    						currentStatus : eStatus,
	   	   	    						lastExecuteTime : eLastExecuteTime,
	   	   	    						executeFailReason : eExecuteFailReason
	   	   	    					}
	   	   	    				});
	   	   	    			}
	   	   	    		});
	   	   	    	}
   	   	    	
      	    	} else {
      	    		clearInterval(refreshIndex);//停止刷新
      	    	}
      	    	disableExecute();
      	    	
      	     }
       	});
    }
    
    function addSystem(){
    	pathTypeChange('git');
    	$("#systemPanel").dialog({    
    	    width:600,    
    	    height:300,
    	    title:'新增系统',
    	    modal:true,
    	    minimizable:false,
    	    buttons :[{
    	    	text:'保存',
                iconCls:'icon-ok',
                handler:function(){
                	saveSystem();
                }
    	    },{
    	    	text:'取消',
                iconCls:'icon-cancel',
                handler:function(){
                    closeSystemPanel();
                }
    	    }]
    	});
    	$("#systemCodeTree").textbox('readonly',false);
    	$('#addSystemForm').form('reset');
    }
    function saveSystem(){
    	
    	if(!$('#addSystemForm').form('validate')){
    		return false;
    	}
    	showProcess();
    	$('#addSystemForm').form('submit',{
			success:function(data){
				closeProcess();
				var data = eval('(' + data + ')');
				if (data.status === 'success') {
       	    		$.messager.alert('温馨提示','新增成功','info');
       	    		$("#systemPanel").dialog('close');
       	    		var selected = $('#systemTree').tree('getSelected');

       	    		$('#systemTree').tree('append', {
       	    			parent: selected.target,
       	    			data: [{
       	    				id: $("#systemCodeTree").val(),
       	    				text: $("#systemCodeTree").val()
       	    			}]
       	    		});
       	    	} else {
       	    		$.messager.alert('温馨提示',data.failReason,'error');
       	    	}
		    } 
		});
    }
    function closeSystemPanel(){
    	$("#systemPanel").dialog('close');
    }
    window.pathTypeChange = function(newValue){
			if(newValue === 'git'){
				$("form").form('enableValidation');
//				$('#filePathTypeBtn').attr('class','trip-unselect');
//				$('#gitPathTypeBtn').attr('class','trip-select');
				$("#gitUserNameTr").show();
				$("#gitBranchTr").show();
				$("#gitPathAddressTr").show();
				$("#filePathAddressTr").hide();
				$("#gitPathAddress").textbox('enableValidation');
				$("#filePathAddress").textbox('disableValidation');
				//$("#gitPathAddress").attr("name","pathAddress");
				//$("#filePathAddress").attr("name","filePathAddress");
			} else {
//				$('#filePathTypeBtn').attr('class','trip-select');
//				$('#gitPathTypeBtn').attr('class','trip-unselect');
				$("#gitUserNameTr").hide();
				$("#gitBranchTr").hide();
				$("#gitUserNameTree").textbox('disableValidation');
				$("#gitPasswordTree").textbox('disableValidation');
				$("#gitBranchTree").textbox('disableValidation');
				$("#sqlPathTree").textbox('disableValidation');
				$("#gitPathAddress").textbox('disableValidation');
				$("#filePathAddress").textbox('enableValidation');
				
			
				
				$("#gitPathAddressTr").hide();
				$("#filePathAddressTr").show();
				
				
			}
		}
    
    function toEditSystem(){
    	var selectedNode = $("#systemTree").tree('getSelected');
    	showProcess();
		$.ajax({
			url : contextPath + systemDetailUrl,
			type : 'post',
			data : {systemCode:selectedNode.id},
			success : function(data){
				closeProcess();
				if(data){
					$("#systemPanel").dialog({    
			    	    width:600,    
			    	    height:300,
			    	    title:'编辑系统',
			    	    modal:true,
			    	    minimizable:false,
			    	    buttons :[{
			    	    	text:'保存',
		                    iconCls:'icon-ok',
		                    handler:function(){
		                    	editSystem();
		                    }
			    	    },{
			    	    	text:'取消',
		                    iconCls:'icon-cancel',
		                    handler:function(){
		                        closeSystemPanel();
		                    }
			    	    }]
			    	});
					$("#systemCodeTree").textbox('readonly');
					$("#systemCodeTree").textbox('setValue',data.systemCode);
					//$("#pathTypeTree").textbox('setValue',data.pathType);
					if(data.pathType === 'git'){
						$('#filePathTypeBtn').attr('class','trip-unselect');
						$('#gitPathTypeBtn').attr('class','trip-select');
						$('#pathTypeTree').val("git");
						$("#gitUserNameTr").show();
						$("#gitBranchTr").show();
						$("#gitPathAddressTr").show();
						$("#filePathAddressTr").hide();
						$("#gitUserNameTree").textbox('setValue',data.gitUserName);
						$("#gitPasswordTree").textbox('setValue','******');
						$("#gitBranchTree").textbox('setValue',data.gitBranch);
						$("#sqlPathTree").textbox('setValue',data.sqlPath);
						$("#gitPathAddress").textbox('setValue',data.pathAddress);
						
						$("#gitPathAddress").textbox('enableValidation');
						$("#filePathAddress").textbox('disableValidation');
					} else {
						$('#gitPathTypeBtn').attr('class','trip-unselect');
						$('#filePathTypeBtn').attr('class','trip-select');
						$('#pathTypeTree').val("file");
						$("#gitUserNameTr").hide();
						$("#gitBranchTr").hide();
						$("#gitPathAddressTr").hide();
						$("#filePathAddressTr").show();
						
						$("#gitUserNameTree").textbox('disableValidation');
						$("#gitPasswordTree").textbox('disableValidation');
						$("#gitBranchTree").textbox('disableValidation');
						$("#sqlPathTree").textbox('disableValidation');
						$("#gitPathAddress").textbox('disableValidation');
						$("#filePathAddress").textbox('enableValidation');
					}
					
					
				}
			}
		})
    }
    
    function editSystem(){
    	
    	if(!$('#addSystemForm').form('validate')){
    		return false;
    	}
    	if($('#pathTypeTree').val() == "file"){
    		$("#gitUserNameTree").textbox('setValue','');
    		$("#gitPasswordTree").textbox('setValue','');
    		$("#gitBranchTree").textbox('setValue','');
    		$("#sqlPathTree").textbox('setValue','');
    		$("#gitPathAddress").textbox('setValue','');
    	}
    	showProcess();
    	$('#addSystemForm').form('submit',{
    		url : contextPath + editSystemUrl,
			success : function(data){
				closeProcess();
				var jsonData = eval('(' + data + ')');
				if (jsonData.status === 'success') {
       	    		$.messager.alert('温馨提示','更新成功','info');
       	    		var node = $("#systemTree").tree('getSelected');
       	    		$("#systemPanel").dialog('close');
       	    		querySystemDetail(node);
       	    	} else {
       	    		$.messager.alert('温馨提示',jsonData.failReason,'error');
       	    	}
		    } 
		});
    }
    
    window.removeEnvironment = function(){
    	var environments = $("#dg").datagrid('getSelections');
    	if(environments === null || environments === '' || environments === undefined || environments.length === 0 ){
    		$.messager.alert('温馨提示','请选择一条数据','warning');
    		return;
    	}
    	$.messager.confirm('确认','您确认想要删除这个环境吗？',function(r){    
    	    if (r){    
    	    	var system = new Object();
    	    	system.systemCode = $("#systemCode").html();
    	    	system.environments = environments;
    	    	showProcess();
    	    	$.ajax({
    	    		 url : contextPath + deleteSystemEnvironmentUrl,
    	    		type : 'post',
    	    		contentType: 'application/json',
    	    	    data : JSON.stringify(system),
    	    	    success : function(data){
    	    	    	closeProcess();
    	    	    	if(data){
    	    	    		if(data.status === 'success'){
    	    	    			var selectNode = $("#systemTree").tree('getSelected');
    	    	    			querySystemDetail(selectNode);
    	        	    	} else {
    	        	    		$.messager.alert('温馨提示',data.failReason,'error');
    	        	    	}
    	    	    	}
    	    	    }
    	    	}); 
    	    }    
    	});
    }
    
    window.removeSystem = function(){
    	$.messager.confirm('确认','您确认想要删除这个系统吗？删除后这个系统的所有信息将被删除！',function(r){    
    	    if (r){
    	    	var systemCode = $("#systemTree").tree('getSelected').id;
    	    	showProcess();
	        	$.ajax({
	       		 url : contextPath + deleteSystemUrl,
	       		type : 'post',
	       		//contentType: 'application/json',
	       	    data : {systemCode : systemCode},
	       	    success : function(data){
	       	    	closeProcess();
	       	    	if(data){
	       	    		if(data.status === 'success'){
	       	    			$.messager.alert('温馨提示','删除成功','info');
	       	    			onloadPage();
	           	    	} else {
	           	    		$.messager.alert('温馨提示',data.failReason,'error');
	           	    	}
	       	    	}
	       	    }
	       	});
        	}    
    	});
    	
    }

